package com.haoze.nurseapp.service.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author embed
 */
public class FeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        String userId = null;
        try {
            userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        } catch (Exception e) {
            userId = "bf533ba10ec64ab0bbf360c44fa7a787";
        }
//        String userId = "bf533ba10ec64ab0bbf360c44fa7a787";
        requestTemplate.header("zuul_id", userId);
    }
//    @Override
//    public void apply(RequestTemplate requestTemplate) {
//        Map<String,String> headers = getHeaders(getHttpServletRequest());
//        for(String headerName : headers.keySet()){
//            System.out.println(headerName + getHeaders(getHttpServletRequest()).get(headerName));
//            requestTemplate.header(headerName, getHeaders(getHttpServletRequest()).get(headerName));
//        }
//    }
//
//    private HttpServletRequest getHttpServletRequest() {
//        try {
//            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//    }
//
//    private Map<String, String> getHeaders(HttpServletRequest request) {
//        Map<String, String> map = new LinkedHashMap<>();
//        Enumeration<String> enumeration = request.getHeaderNames();
//        while (enumeration.hasMoreElements()) {
//            String key = enumeration.nextElement();
//            if(needThisHeader(key)){
//                String value = request.getHeader(key);
//                map.put(key, value);
//            }
//        }
//        return map;
//    }
//
//    private boolean needThisHeader(String headerName) {
//        if (headerName.equals("zuul_id")) {
//            return true;
//        } else {
//            return false;
//        }
//        //todo:这里写你的逻辑，哪些header需要传递，千万不能把所有的header传下去
////        return true;
//    }
}
